#!/usr/bin/python
# GM_WriteVariables.py

import numpy
from os import mkdir
from os import linesep

def WV(variables,variablenames,filename,filefolder):
    '''Writes variables to file in a form recoverable via python import.

    variables and variablenames must be lists of the same length; variablenames must contain strings that are allowed python variable names.  filename should end in .py and filefolder should be an existing folder.'''
    fullfilename = filefolder+filename
    try:
        outfile = open(fullfilename, 'w')
    except IOError:
        print 'The output folder', filefolder, 'does not exist.  Attempting to create it.'
        mkdir(filefolder)
        outfile = open(fullfilename, 'w')
    header = "# " + filename + 2*linesep + "import numpy" + 2*linesep
    outfile.write(header)
    body = ''
    for i in range(0, len(variables)):
        entry = variables[i]
        if type(entry) == numpy.ndarray:
            entry = list(entry)
            entry = str(entry)
            entry = 'numpy.array('+entry+')'
        elif type(entry) == dict:
            entry = str(entry)
            entry = entry.replace(' array([', ' numpy.array([')
        else:
            entry = str(entry)
        body = body + variablenames[i] + " = " + entry + 2*linesep
    outfile.write(body)
    outfile.close()
